package com.chatai.controller;

import com.chatai.model.ApiKey;
import com.chatai.model.User;
import com.chatai.service.ApiKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@RestController
@RequestMapping("/api/keys")
public class ApiKeyController {
    
    @Autowired
    private ApiKeyService apiKeyService;
    
    /**
     * 创建新的API Key
     */
    @PostMapping("/create")
    public ResponseEntity<?> createApiKey(@RequestParam("description") String description,
                                         @RequestParam("expiresInDays") Integer expiresInDays) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) auth.getPrincipal();
        
        LocalDateTime expiresAt = null;
        if (expiresInDays != null && expiresInDays > 0) {
            expiresAt = LocalDateTime.now().plus(expiresInDays, ChronoUnit.DAYS);
        }
        
        ApiKey apiKey = apiKeyService.createApiKey(user, description, expiresAt);
        
        return ResponseEntity.ok()
            .body("{" +
                "\"apiKey\":\"" + apiKey.getKeyValue() + "\"," +
                "\"description\":\"" + apiKey.getDescription() + "\"," +
                "\"createdAt\":\"" + apiKey.getCreatedAt() + "\"," +
                "\"expiresAt\":" + (apiKey.getExpiresAt() != null ? "\"" + apiKey.getExpiresAt() + "\"" : "null") +
                "}");
    }
    
    /**
     * 获取当前用户的所有API Key
     */
    @GetMapping("/list")
    public ResponseEntity<?> getUserApiKeys() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) auth.getPrincipal();
        
        List<ApiKey> apiKeys = apiKeyService.getUserApiKeys(user.getId());
        return ResponseEntity.ok(apiKeys);
    }
    
    /**
     * 删除API Key
     */
    @DeleteMapping("/{keyId}")
    public ResponseEntity<?> deleteApiKey(@PathVariable Long keyId) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) auth.getPrincipal();
        
        apiKeyService.deleteApiKey(keyId, user.getId());
        return ResponseEntity.ok("{\"message\":\"API Key deleted successfully\"}");
    }
    
    /**
     * 禁用API Key
     */
    @PutMapping("/{keyId}/deactivate")
    public ResponseEntity<?> deactivateApiKey(@PathVariable Long keyId) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) auth.getPrincipal();
        
        apiKeyService.deactivateApiKey(keyId, user.getId());
        return ResponseEntity.ok("{\"message\":\"API Key deactivated successfully\"}");
    }
    
    /**
     * 启用API Key
     */
    @PutMapping("/{keyId}/activate")
    public ResponseEntity<?> activateApiKey(@PathVariable Long keyId) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) auth.getPrincipal();
        
        apiKeyService.activateApiKey(keyId, user.getId());
        return ResponseEntity.ok("{\"message\":\"API Key activated successfully\"}");
    }
    
    /**
     * 验证API Key是否有效（公共接口）
     */
    @GetMapping("/validate")
    public ResponseEntity<?> validateApiKey(@RequestParam("apiKey") String apiKey) {
        boolean isValid = apiKeyService.isValidApiKey(apiKey);
        return ResponseEntity.ok("{\"valid\":" + isValid + "}");
    }
}